<template>
  <div class="home">
    <div class="dom">
      <el-button @click="getView">获取view信息</el-button>
      <el-button @click="setPolyon">模拟添加高度信息</el-button>
    </div>
    <div ref="mapCon" id="mapCon"></div>
    <div id="anchor">
      <span class="text">监控点</span>
      <img
        src="https://img0.baidu.com/it/u=2174002721,1596527148&fm=253&fmt=auto&app=138&f=JPEG?w=534&h=480"
      />
    </div>
    <div class="pointerList" id="pointlist">
      <div v-for="(item, index) in arrPoint" :key="index">
        {{ item.name }}
      </div>
    </div>
  </div>
</template>
  
  <script>
import "ol/ol.css";
import { ref, onMounted, defineComponent } from "vue";
import { Map, View } from "ol";
import OSM from "ol/source/OSM.js";
import TileLayer from "ol/layer/Tile";
import XYZ from "ol/source/XYZ";
import { fromLonLat } from "ol/proj";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import GeoJSON from "ol/format/GeoJSON";
import Feature from "ol/Feature";
import { LineString, Point, Polygon } from "ol/geom";
import { Icon, Style, Stroke, Circle, Fill, Text } from "ol/style";
import Overlay from "ol/Overlay.js";
// import yzm from "@/assets/stationicon.png";
import jsonData from "./120116.json";
import { Image as ImageLayer } from "ol/layer.js";
import ImageWMS from "ol/source/ImageWMS.js";

import VectorTileSource from "ol/source/VectorTile";
import VectorTileLayer from "ol/layer/VectorTile";
import MVT from "ol/format/MVT";

import gamer from "./gamer.jpg";
import { defaults } from "ol/interaction/defaults";
import PointerInteraction from "ol/interaction/Pointer";
import DragPan from "ol/interaction/DragPan";

export default defineComponent({
  name: "Home",
  components: {},
  setup() {
    const mapCon = ref(null);
    const animating = ref(false);
    let map;
    let arrPoint = ref([]);
    let polyonArr = ref([]);

    onMounted(async () => {
      console.log(import.meta.env);
      // 地图的矢量图层
      // const layer = new TileLayer({
      //   source: new OSM(),
      // });
      map = new Map({
        // layers: [tdtVectorLayer, layer],
        // layers: [layer],
        layers: [
          // new TileLayer({
          //   title: "天地图矢量图层",
          //   source: new XYZ({
          //     // url: 'https://webst01.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}'
          //     url: "https://webrd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}",
          //   }),
          // }),
          // new ImageLayer({
          //   source: new ImageWMS({
          //     url: "/geoserver/bcd/wms",
          //     params: { LAYERS: "bcd", VERSION: "1.1.1" },
          //     ratio: 1,
          //     serverType: "geoserver",
          //   }),
          // }),
          new ImageLayer({
            source: new ImageWMS({
              url: "/geoserver/wms",
              params: { LAYERS: "mytianjin", VERSION: "1.1.1" },
              ratio: 1,
              serverType: "geoserver",
            }),
          }),
          // new VectorLayer({
          //   source: new VectorSource({
          //     url: "./120116.json",
          //     format: new GeoJSON(),
          //   }),
          //   style: new Style({
          //     fill: new Fill({
          //       color: "rgba(255,0,0,0.2)",
          //     }),
          //     stroke: new Stroke({
          //       color: "#3399CC",
          //       width: 3,
          //     }),
          //   }),
          // }),
        ],
        target: mapCon.value,
        view: new View({
          // center: fromLonLat([117.28, 39.54]),
          // center: [117.28, 39.54],
          center: [117.71166692770711, 38.98915753246808],
          projection: "EPSG:4326",
          minZoom: 4,
          zoom: 15.5,
          // extent: [102, 29, 117, 39],
          // extent: [
          //   117.71803149476399, 38.994363897369794,
          //   117.77213793300834, 39.0227068100564,
          // ],
        }),
        interactions: defaults({
          doubleClickZoom: true,
        }),
      });
      // 打点方法
      // 1、初始化点位的图层
      let pointLayer = new VectorLayer({
        source: new VectorSource(),
      });

      // 2、创建点位的feature

      let feature = new Feature({
        geometry: new Point([117.74064594340295, 39.00908399100884]),
        attrs: {
          type: "point",
          name: "点位1",
          url: "http://10.198.12.12.m3u8",
        },
        draggable: true,
      });

      feature.setStyle(
        new Style({
          image: new Icon({
            src: gamer,
            width: 40,
            height: 40,
          }),
        })
      );

      // 3 、 将feature添加到layer中
      pointLayer.getSource().addFeatures([feature]);

      // 4、将feauture添加到layser

      map.addLayer(pointLayer);

      // 创建一条线
      let linefeature = new Feature({
        geometry: new LineString([
          [117.28, 39.54],
          [117.80182220401787, 39.31002258107163],
        ]), // 多边形
      });

      linefeature.setStyle(
        new Style({
          stroke: new Stroke({
            color: "green",
            width: 9,
          }),
        })
      );

      pointLayer.getSource().addFeatures([linefeature]);

      // 创建一个面
      let areafeature = new Feature({
        geometry: new Polygon([
          [
            [117.61003159002942, 39.428269425786304],
            [117.44996573925711, 39.303533424959234],
            [117.80182220401787, 39.31002258107163],
          ],
        ]), // 多边形
      });

      areafeature.setStyle(
        new Style({
          stroke: new Stroke({
            color: "pink",
            width: 2,
          }),
          fill: new Fill({
            color: "rgba(255,255,255,0.9)",
          }),
        })
      );

      pointLayer.getSource().addFeatures([areafeature]);

      //创建一个dom元素

      const popup = new Overlay({
        element: document.getElementById("anchor"),
      });
      popup.setPosition([117.28, 39.54]);
      map.addOverlay(popup);

      // pointLayer.getSource().addFeature(linefeature);

      // 地图注册点击事件
      map.on("click", (e) => {
        console.log(e);
        let point = e.coordinate;
        console.log(point);
        polyonArr.value.push(point);
      });

      map.on("postrender", () => {
        // 在地图缩放时重新计算渐变
        // cachedGradient.value = createGradient(polygon);
      });

      // 区域添加蒙版效果
      debugger;
      // 定义外部大矩形（覆盖整个地球）
      const outerRing = [
        [-180, -90],
        [-180, 90],
        [180, 90],
        [180, -90],
        [-180, -90],
      ];

      // 定义内层多边形区域（您可以根据需要调整区域坐标）
      const innerRing = [
        [117.71166692770711, 38.98915753246808],
        [117.71553637720841, 38.98362974746624],
        [117.71516785820829, 38.977364924464155],
        [117.71885304820951, 38.97294269646269],
        [117.73764751721575, 38.96372972145962],
        [117.87399954726108, 38.929088935448114],
        [117.88155418676358, 38.93553801795026],
        [117.87584214226169, 38.93645931545056],
        [117.87842177526254, 38.94585654995368],
        [117.84414950825115, 38.95359544895626],
        [117.80766612723903, 38.95986027195834],
        [117.80821890573921, 38.9633612024595],
        [117.76012717622322, 38.97202139896238],
        [117.75773180272243, 38.97165287996226],
        [117.75367809372108, 38.97294269646269],
        [117.75386235322114, 38.97441677246318],
        [117.74686049221881, 38.976996405464035],
        [117.74667623271876, 38.97625936746379],
        [117.73211973221392, 38.98123437396544],
        [117.73138269421368, 38.97994455746501],
        [117.72419657371128, 38.98307696896605],
        [117.72419657371128, 38.984551044966544],
        [117.71922156720963, 38.985840861466976],
        [117.71940582670969, 38.98694641846734],
        [117.71203544670725, 38.98897327296802],
      ];

      const innerRing2 = [
        [117.71999684330913, 39.00776477167736],
        [117.7318497047607, 39.003581408812096],
        [117.72435451296045, 38.991205627002365],
        [117.72296005867203, 38.99242577450473],
        [117.72069407045333, 38.991205627002365],
        [117.71964822973702, 38.99312300164895],
        [117.71407041258334, 38.99207716093263],
        [117.71180442436466, 38.99260008129079],
      ];
      const innerRing3 = [
        [117.71999684330913, 39.00776477167736],
        [117.7318497047607, 39.003581408812096],
        [117.72435451296045, 38.991205627002365],
        [117.72296005867203, 38.99242577450473],
        [117.72069407045333, 38.991205627002365],
        [117.71964822973702, 38.99312300164895],
        [117.71407041258334, 38.99207716093263],
        [117.71180442436466, 38.99260008129079],
      ];

      const innerRing4 = [
        [117.73239413935512, 39.00355603914005],
        [117.7249117338587, 38.99037807125083],
        [117.7419984210371, 38.98445915347008],
        [117.7476939834299, 38.98658102965563],
        [117.74624217340819, 38.98222559959055],
        [117.75026257039136, 38.985575930409844],
        [117.75472967815041, 38.98367740961224],
        [117.7571865874179, 38.97831688030138],
        [117.75774497588779, 38.983119021142365],
        [117.76176537287094, 38.98155553342669],
        [117.76221208364684, 38.97708842566763],
        [117.76533905907819, 38.976530037197755],
        [117.76522738138421, 38.980103723405],
        [117.78644614323973, 38.97407312793027],
        [117.78879137481323, 38.97753513644354],
        [117.77963380390716, 38.985910963491776],
        [117.76254711672877, 39.044988463605314],
        [117.75975517437936, 39.04733369517882],
        [117.76198872825888, 39.05046067061016],
        [117.77393824151437, 39.04677530670894],
        [117.77628347308787, 39.05347596834752],
        [117.73875976791179, 39.062298506171665],
        [117.73697292480816, 39.05269422448969],
        [117.74702391726605, 39.047445372872794],
        [117.74211009873108, 39.035830892699245],
        [117.7462421734082, 39.034602438065505],
        [117.74546042955038, 39.03248056187995],
        [117.75283115735282, 39.02946526414259],
        [117.74903411575762, 39.02242956942207],
        [117.76165369517696, 39.01773910627506],
        [117.76835435681555, 38.99060142663878],
        [117.73328756090694, 39.00355603914005],
      ];

      // 创建多边形（带洞）
      // const polygon = new Polygon([outerRing, innerRing]);
      // const polygon1 = new Polygon([outerRing, innerRing2]);
      // const polygon2 = new Polygon([outerRing, innerRing4]);
      // const polygon = new Polygon([innerRing]);
      const polygon1 = new Polygon([innerRing2]);
      const polygon2 = new Polygon([innerRing4]);
      // .transform(
      //   "EPSG:4326",
      //   "EPSG:3857"
      // );

      // let colorGradent = await getCenterGradientStyle(polygon)
      // 创建一个渐变色填充

      // 创建一个矢量图层以显示蒙版
      const maskLayer = new VectorLayer({
        source: new VectorSource({
          features: [
            // new Feature(polygon),
            new Feature(polygon1),
            new Feature(polygon2),
          ],
        }),
        style: new Style({
          fill: new Fill({
            color: "rgba(0,0,0,0.4)", // 蒙版颜色
            // color: pattern,
          }),
          stroke: new Stroke({
            color: "red",
            width: 2,
          }),
        }),
      });
      // maskLayer.getSource().getFeatures()[0].setStyle(
      //   new Style({
      //     renderer(coordinates, state) {
      //       debugger
      //       const [[x, y], [x1, y1]] = coordinates;
      //       const ctx = state.context;
      //       const dx = x1 - x;
      //       const dy = y1 - y;
      //       const radius = Math.sqrt(dx * dx + dy * dy);

      //       const innerRadius = 0;
      //       const outerRadius = radius * 1.4;

      //       const gradient = ctx.createRadialGradient(
      //         x,
      //         y,
      //         innerRadius,
      //         x,
      //         y,
      //         outerRadius
      //       );
      //       gradient.addColorStop(0, "rgba(255,0,0,0)");
      //       gradient.addColorStop(0.6, "rgba(255,0,0,0.2)");
      //       gradient.addColorStop(1, "rgba(255,0,0,0.8)");
      //       ctx.beginPath();
      //       ctx.arc(x, y, radius, 0, 2 * Math.PI, true);
      //       ctx.fillStyle = gradient;
      //       ctx.fill();

      //       ctx.arc(x, y, radius, 0, 2 * Math.PI, true);
      //       ctx.strokeStyle = "rgba(255,0,0,1)";
      //       ctx.stroke();
      //     },
      //   })
      // );
      // 添加蒙版层到地图
      map.addLayer(maskLayer);
      map.render();
      // 自定义点位拖拽事件
      // 目标 DOM 容器
      const targetDom = document.getElementById("pointlist"); // 替换为实际容器的 ID
      // 全局变量
      let draggingFeature = null;
      let isDragging = false;
      // 获取 DragPan 交互
      const dragPanInteraction = map
        .getInteractions()
        .getArray()
        .find((interaction) => interaction instanceof DragPan);
      // 监听地图上的长按事件
      map.on("pointerdown", (evt) => {
        // 检查是否点击在图标上
        map.forEachFeatureAtPixel(evt.pixel, (feature) => {
          if (feature.get("draggable")) {
            isDragging = true;
            // 禁用地图拖动
            if (dragPanInteraction) {
              dragPanInteraction.setActive(false);
            }
            // 创建一个新的图标
            draggingFeature = new Feature({
              geometry: feature.getGeometry().clone(),
              attrs: feature.getProperties().attrs,
            });

            // 设置样式和属性
            draggingFeature.setStyle(
              new Style({
                image: new Icon({
                  src: gamer,
                  scale: 0.3,
                  opacity: 0.5, // 半透明表示拖动状态
                }),
                text: new Text({
                  text: "拖动到视频区域松开鼠标",
                  offsetY: -25, // 文字位置
                  font: "12px Arial",
                  fill: new Fill({ color: "#000" }), // 文字颜色
                  stroke: new Stroke({ color: "#fff", width: 2 }), // 描边
                }),
              })
            );

            pointLayer.getSource().addFeature(draggingFeature);
          }
        });
        // 拖拽操作
        map.on("pointermove", (evt) => {
          if (isDragging && draggingFeature) {
            const coords = evt.coordinate; // 获取当前拖动位置
            draggingFeature.getGeometry().setCoordinates(coords); // 更新图标位置
          }
        });
        // 释放鼠标事件
        map.on("pointerup", (evt) => {
          if (isDragging && draggingFeature) {
            const pixel = map.getPixelFromCoordinate(evt.coordinate);

            // 检查是否在 DOM 元素上释放鼠标
            const elementAtPixel = document.elementFromPoint(
              pixel[0],
              pixel[1]
            );

            if (targetDom.contains(elementAtPixel)) {
              // console.log(draggingFeature.getProperties().attrs)
              arrPoint.value.push(draggingFeature.getProperties().attrs);
            }

            // 删除复制的图标
            pointLayer.getSource().removeFeature(draggingFeature);
            draggingFeature = null;
            isDragging = false;

            // 重新启用地图拖动
            if (dragPanInteraction) {
              dragPanInteraction.setActive(true);
            }
          }
        });
      });
    });

    const getView = () => {
      localStorage.setItem("polython", JSON.stringify(polyonArr.value));
      return;
      let view = map.getView();
      let center = view.getCenter();
      console.log(center);
      center[0] = center[0] - 1;
      center[1] = center[1] - 1;
      view.setCenter(center);
      map.render();

      view.animate({
        // center: fromLonLat([114.28, 34.54]),
        center: [114.28, 34.54],
        zoom: 7,
        duration: 1000,
      });

      // 获取图层方法:等等
      // map.getLayers().item[1].getSource().on('click')
    };

    const setPolyon = () => {
      // 创建一个多边形要素的数据集，假设每个多边形有一个高度属性
      var features = [
        new Feature({
          geometry: new Polygon([
            [
              [117.69513238288741, 39.015957906515624],
              [117.69335591431309, 39.013219184130215],
              [117.69772306622495, 39.01114663746018],
              [117.69986963241892, 39.01462555508489],
            ],
          ]),
          height: 20,
        }),
        new Feature({
          geometry: new Polygon([
            [
              [117.69513238288741, 39.015957906515624],
              [117.69335591431309, 39.013219184130215],
              [117.69772306622495, 39.01114663746018],
              [117.69986963241892, 39.01462555508489],
            ],
          ]),
          height: 10,
        }),
      ];

      // 创建样式函数，根据每个面数据的高度进行样式设置
      var styleFunction = function (feature) {
        alert(1);
        var height = feature.get("height"); // 获取每个面数据的高度
        var color =
          height > 15 ? "rgba(255, 0, 0, 0.8)" : "rgba(0, 0, 255, 0.8)";

        return new Style({
          fill: new Fill({
            color: color,
          }),
          stroke: Stroke({
            color: "black",
            width: 2,
          }),
        });
      };

      // 创建 VectorSource 和 VectorLayer
      var vectorSource = new VectorSource({
        features: features,
      });
      var vectorLayer = new VectorLayer({
        source: vectorSource,
        style: function (feature) {
          console.log(feature)
          // 获取要素的属性
          var height = feature.get("height");

          // 根据属性值返回不同的样式
          var color =
            height > 15 ? "rgba(255, 0, 0, 0.8)" : "rgba(0, 0, 255, 0.8)";

          return new ol.style.Style({
            fill: new ol.style.Fill({
              color: color, // 填充颜色根据高度变化
            }),
            stroke: new ol.style.Stroke({
              color: "black",
              width: 2,
            }),
          });
        },
      });
      debugger;
      // 添加 VectorLayer 到地图
      map.addLayer(vectorLayer);
      map.render();
    };
    return { mapCon, animating, getView, arrPoint, setPolyon };
  },
});
</script>
  
  <style lang="scss">
.dom {
  position: absolute;
  z-index: 999;
  left: 50px;
  top: 100px;
}
.home {
  width: 100%;
  height: 100%;
}
#menu {
  margin-bottom: 20px;
}

#mapCon {
  width: 100vw;
  height: 100vh;
}
#anchor {
  position: relative;
  height: 130px;
  &:hover {
    .text {
      display: block;
    }
  }
  .text {
    display: none;
  }
  img {
    position: absolute;
    width: 30px;
    height: 30px;
    animation: myflash 3s;
    // animation-delay: 2s;
    animation-iteration-count: infinite; //2
    animation-timing-function: ease-in;
    border-radius: 50%;
    left: 0;
    bottom: 0;
  }
  @keyframes myflash {
    0% {
      bottom: 0;
    }
    50% {
      bottom: 30px;
    }
    100% {
      bottom: 0px;
    }
  }
}

.pointerList {
  width: 200px;
  height: 100%;
  position: fixed;
  right: 0;
  top: 0;
  background: #fff;
  z-index: 999;
  opacity: 0.8;
}
</style>
  